<template>
  <div class="room-main">
    <Loading />
    <div v-if="loaded" ref="main" id="main">
      <HorseLamp />
      <div class="class-panel">
        <WhiteBorad />
        <DocumentManager v-if="!_isStudent" />
      </div>
      <div class="media-panel">
        <div @click="handleClose" v-show="exitScreenEvent" class="screen">
          <img src="@/assets/home/screen-icon.png" />
          <span>退出全屏</span>
        </div>
        <!-- 121班型 -->
        <div v-if="/_121/.test(classMode)">
          <div v-if="!_isStudent" class="live-teacher-player">
            <SelfTeacherPlayer />
          </div>
          <div v-if="!_isStudent" class="action-list">
            <ActiveList />
          </div>
          <!-- 老师播放器 -->
          <div v-if="_isStudent" class="live-teacher-player">
            <TeacherPlayer />
          </div>
          <!-- 自己播放器 -->
          <div v-if="_isStudent" class="live-student-player">
            <SelfPlayer />
          </div>
          <div class="interaction-panel">
            <InteractionPanel />
          </div>
        </div>
        <!-- 小班班型 -->
        <div v-if="/_SMALL/i.test(classMode)">
          <div class="small-panel">
            <SmallPanel />
          </div>
        </div>
      </div>
      <div class="footer">
        <SettingPanel @models="changeModel"/>
        <FunctionPanel />
      </div>
      <!-- 模态框组件 -->
      <ModalPanel />
    </div>
  </div>
</template>
<!-- 本 SDK 需要使用 JQuery 库，因此在使用之前首先引入 JQuery 文件 -->
<script>
import Loading from "@/components/Room/Loading.vue";
// 白板组件
import WhiteBorad from "@/components/Room/WhiteBoard.vue";
// 设置面板：扬声器、麦克风、摄像头、设置
import SettingPanel from "@/components/Room/SettingPanel";
// 交互面板：用户列表、聊天、发言列表
import InteractionPanel from "@/components/Room/InteractionPanel";
// 老师播放器
import TeacherPlayer from "@/components/Room/TeacherPlayer";
import SelfTeacherPlayer from "@/components/Room/SelfTeacherPlayer";
// 功能面板：直播间的一些功能，举手、屏幕共享、弹幕之类
import FunctionPanel from "@/components/Room/FunctionPanel";
// 模态框组件，在老师端发起互动后显示
import ModalPanel from "@/components/Room/ModalPanel";
// 跑马灯组件
import HorseLamp from "@/components/Room/HorseLamp";
// 话术
import language from "@/language/main.js";
// 课件
import DocumentManager from "@/components/Room/DocumentManager.vue";
// 自己播放器
import SelfPlayer from '@/components/Room/SelfPlayer'
import ActiveList from '@/components/Room/InteractionPanel/ActiveList'
// 小班面板
import SmallPanel from "@/components/Room/InteractionPanel/SmallPanel";

import md5 from 'md5';

BJY.eventEmitter.OPEN_DOC_IN_CATALOGUE = 'open_doc_in_catalogue';
BJY.eventEmitter.ZWZ_CLASS_OVER = 'zwz_class_over';
BJY.eventEmitter.ZWZ_CLASSING_START = 'zwz_classing_start';
BJY.eventEmitter.ZWZ_CLASSING_NOSTART = 'zwz_classing_nostart';
BJY.eventEmitter.ZWZ_CLASS_BEFORE = 'zwz_class_before';
BJY.eventEmitter.ZWZ_CLASS_END = 'zwz_class_end';
BJY.eventEmitter.ZWZ_SETTUB_INIT = 'zwz_settub_init';
BJY.eventEmitter.ZWZ_PAD_CMD = 'zwz_pad_cmd';
BJY.eventEmitter.ZWZ_PAD_FORBID = 'zwz_pad_forbid';
BJY.eventEmitter.ZWZ_PAD_FORBID_INIT = 'zwz_pad_forbid_init';
BJY.eventEmitter.ZWZ_SETBTN_CLASSEND = 'zwz_setbtn_classend';
let eventEmitter = BJY.eventEmitter;
let auth = BJY.auth;

import {
  getQueryString, isClient
} from '@/utils/tools'

function checkFull() {
    var isFull = document.fullscreen || window.fullScreen || document.webkitIsFullScreen || document.msFullscreenEnabled;
    return !!isFull;
}

export default {
  name: "bjyRoom",
  components: {
    ActiveList,
    SelfPlayer,
    Loading,
    WhiteBorad,
    DocumentManager,
    SettingPanel,
    SmallPanel,
    InteractionPanel,
    TeacherPlayer,
    SelfTeacherPlayer,
    FunctionPanel,
    HorseLamp,
    ModalPanel
  },
  data() {
    return {
      exitScreenEvent: false,
      hasPad: false,
      classMode: '',
      _isStudent: false,
      loaded: false,
      webrtc: 1,
      isEye: false
    };
  },
  mounted() {
    /**
     * flash的奇怪特性（普通大班课使用了flash）；
     * 需要在页面中插入一个大尺寸的flash才会自动播放，否则将会导致无法上麦和视频无法自动播放的问题
     */
    // var url =
    //   "//live-cdn.baijiayun.com/js-sdk/1.15.0/player/extension/flash.swf";
    // var html = BJY.createSWF("temp", "", url);

    // var swf = $(html);
    // $("body").prepend(swf);
    // swf.css({
    //   position: "absolute",
    //   top: 0,
    //   width: 398,
    //   height: 298,
    //   opacity: 0
    // });
    // 判断是否支持flash
    // if (!this.supportFlash() && !this.webrtc) {
    //   this.$Dialog
    //     .show({
    //       title: "提示",
    //       content: `网页Flash插件加载不成功，请重新<a class="opt-button"
    //         href="http://www.adobe.com/go/getflashplayer">启用flash</a>`,
    //       confirmText: "关闭"
    //     })
    //     .then(() => {
    //       console.log("flash启用");
    //     })
    //     .catch(e => {
    //       console.log(e);
    //     });
    // }
    // webrtc 添加页面交互
    // if (this.webrtc) {
    //   this.$Dialog
    //     .show({
    //       title: "提示",
    //       content: `正在进入教室。。。`,
    //       confirmText: "确认"
    //     })
    //     .then(() => {
    //       console.log("教室内首次交互完成");
    //     })
    //     .catch(e => {
    //       console.log(e);
    //     });
    // }
  },
  created() {
    let that = this
    let $body = $("body");
    let store = BJY.store

    that._isStudent = that.$store.state.userInfo.is_assist == 0
    store.set('yxp_class_mode', getQueryString('class_mode') || that.$route.query.class_mode || 'PAD_121')
    that.classMode = store.get('yxp_class_mode')
    store.set('yxp_has_pad', !!(getQueryString('has_pad') || that.$route.query.has_pad))
    that.hasPad = store.get('yxp_has_pad')

    eventEmitter
      .one(eventEmitter.CLASSROOM_CONNECT_TRIGGER, (event, data) => {
        // 初始化扩展
        var extension = BJY.getExtension();
        // 如果您使用的是webrtc拓展的话，请确保引入了realtimecat.js这个依赖，否则此处会报undefined：RTCat
        extension.init().then(() => {
          eventEmitter.trigger(eventEmitter.CLASSROOM_CONNECT_TRIGGER, data);
        });
        return false;
      })
      .on(eventEmitter.CLASSROOM_CONNECT_FAIL, () => {
        alert(language.ROOM_SERVER_CONNECT_FAIL);
      })
      .on(eventEmitter.LOGIN_CONFLICT, () => {
        alert(language.LOGIN_CONFLICT);
        // 冲突时退出直播间
        window.location.href = `?r=${Math.random()}#/mycourse`
      })
      // 监听初始化事件，初始化组件
      // 请将所有的组件创建逻辑写于此回调函数之中
      .one(eventEmitter.VIEW_RENDER_TRIGGER, () => {
        // 注意，在VIEW_RENDER_TRIGGER事件触发后再去加载教室里面的组件
        this.loaded = true;

        eventEmitter.trigger(eventEmitter.DOC_ALL_REQ);

        if (auth.isStudent()) {
          $body.addClass("student");
        }

        // 初始化webRTC的屏幕扩展
        // 如果你需要使用到webrtc屏幕共享的话，记得在index.html里面引入对应的js依赖
        if (auth.isWebRTC()) {
          BJY.ScreenShareExtensionWebrtc.init();
        }

      })
      .one(eventEmitter.LOADING_PANEL_END, () => {
        // 初始化教室封面状态
        this.setThumbInit()
        // 进度条加载完成再显示ui
        $("#main").css("opacity", 1);
      })
      .on(eventEmitter.CLASS_START, () => {
        // 自动发言-实时加载
        if (auth.isStudent()) {
          if(/_121/i.test(that.classMode)){
            eventEmitter.trigger(eventEmitter.MEDIA_SWITCH_TRIGGER, {
              audioOn: true,
              videoOn: true
            })
          }else if(/_SMALL/i.test(that.classMode)){
            eventEmitter.trigger(eventEmitter.MEDIA_SWITCH_TRIGGER, {
              audioOn: false,
              videoOn: true
            })
          }
        }
        // 上课后老师自动开启音视频
        if (auth.isTeacher()) {
          eventEmitter.trigger(eventEmitter.MEDIA_SWITCH_TRIGGER, {
            audioOn: true,
            videoOn: true
          });
        }

        setTimeout(() => {
          this.setThumbInit()
        }, 500)
      })
      .on(eventEmitter.CLASS_END, () => {
        // 下课后所有人自动关闭音视频
        eventEmitter.trigger(eventEmitter.MEDIA_SWITCH_TRIGGER, {
          audioOn: false,
          videoOn: false
        });

        eventEmitter.trigger(eventEmitter.ZWZ_CLASS_END)
      })
      .on(eventEmitter.CLASSROOM_CONNECT_SUCCESS, (event, data) => {
        // data.reconnect 是否为断线重连
        if(data.reconnect){
          // 注意，在VIEW_RENDER_TRIGGER事件触发后再去加载教室里面的组件
          this.loaded = true;

          eventEmitter.trigger(eventEmitter.DOC_ALL_REQ);

          if (auth.isStudent()) {
            $body.addClass("student");
          }

          // 初始化webRTC的屏幕扩展
          // 如果你需要使用到webrtc屏幕共享的话，记得在index.html里面引入对应的js依赖
          if (auth.isWebRTC()) {
            BJY.ScreenShareExtensionWebrtc.init();
          }
        }
      })
      .on(
        eventEmitter.USER_ADD, // 用户加入
        (event, data) => {
          if(data && data.userList){
            this.setThumbInit()
            for(let user of data.userList){
              if(user.type == 0){
                console.log('学生加入', user)
              }else{
                console.log('老师加入', user)
              }
            }
          }
        }
      )
      .on(
        eventEmitter.USER_REMOVE, // 用户离开
        (event, data) => {
          if(data && data.user){
            // 处理隐身用户-监课
            if(/_121/i.test(this.classMode) && Number(data.user.status) == 0){
              eventEmitter.trigger(eventEmitter.ZWZ_PAD_FORBID_INIT)
            }
            this.setThumbInit()
            let user = data.user
            if(user.type == 0){
              console.log('学生离开', user)
            }else{
              console.log('老师离开', user)
            }
          }
        }
      )
      .on(
        eventEmitter.ZWZ_SETTUB_INIT,
        (event, data) => {
          this.setThumbInit()
        }
      )
      .on(
        eventEmitter.MEDIA_SWITCH_TRIGGER,
        (event, data) => {
          if(/_SMALL/i.test(that.classMode) && auth.isStudent()){
            // data.operator
            if(data.audioOn){//小班发言
              BJY.api.sendBroadcast(
                'YXP_SPEAK_NOTICE',
                {
                  speak: true,
                  uid: store.get('user.id'),
                }
              )
            }else{//小班终止发言
              BJY.api.sendBroadcast(
                'YXP_SPEAK_NOTICE',
                {
                  speak: false,
                  uid: store.get('user.id'),
                }
              )
            }
          }
        }
      )

    // 监听播放器退出全屏
    window.onresize = function() {
      setTimeout(() => {
        if (!checkFull()) {
          that.exitScreenEvent = false
          eventEmitter.trigger(eventEmitter.FULLSCREEN_EXIT_TRIGGER);
        } else {
          that.exitScreenEvent = true
        }
      }, isClient() ? 500 : 0)
    }
    // 初始化教室
    this.init()
  },
  beforeDestroy () {
    BJY.eventEmitter.off('.yxp')
    BJY.dispose(BJY.config.BJY_DISPOSE_TYPE_OUT_ROOM)
  },
  methods: {
    handleClose () {
      eventEmitter.trigger(eventEmitter.FULLSCREEN_EXIT_TRIGGER);
    },
    changeModel (val) {
      console.log(123456789 + val)
      this.isEye = !this.isEye
      console.log(this.isEye)
      this.$emit('eyeModel', this.isEye)
    },
    setThumbInit () {
      let that = this
      let $T = new Date().getTime()
      let eventEmitter = BJY.eventEmitter
      // 忽略隐身用户
      let userList = BJY.data.user.all().filter((v)=>{return v.status === 0})
      let bclass = BJY.store.get('class')
      if(!that.loaded) return false
      if(bclass && (1 || /_121/.test(that.classMode))){
        if($T > (+bclass.endTimeTs + +bclass.endDelayTime)){//课后
          // 已下课
          eventEmitter.trigger(eventEmitter.ZWZ_CLASS_OVER, {
            classMode: that.classMode
          })
        }else if($T > bclass.startTimeTs){//课中
          if(bclass.started){//正在上课
            eventEmitter.trigger(eventEmitter.ZWZ_CLASSING_START, {
              classMode: that.classMode,
              count: userList.length
            })
          }else{//未上课
            eventEmitter.trigger(eventEmitter.ZWZ_CLASSING_NOSTART, {
              classMode: that.classMode,
              count: userList.length
            })
          }
        }else{//课前
          eventEmitter.trigger(eventEmitter.ZWZ_CLASS_BEFORE, {
            classMode: that.classMode,
            count: userList.length
          })
        }
      }
    },
    makeSign (pars, partner_key = '') {
      partner_key = partner_key || 'G3PZ3g7RiYN5xsMW7PV8pYlVajRZ7hrahVwkVHKi5G2vdLnacbe4iqwe+yLkA887OdOaeOTNekHYcfN8IA9BgVellxHR'
      let arr = [];
      let need = ['room_id', 'user_avatar', 'user_name', 'user_number', 'user_role']
      for (var key in pars) {
        if(need.indexOf(key) !== -1) arr.push(key)
      }
      arr.sort();
      let str = '';
      for (var i in arr) {
        str += arr[i] + "=" + pars[arr[i]] + "&"
      }
      console.log('yxp.makeSign.params', `${str}partner_key=${partner_key}`)
      return md5(`${str}partner_key=${partner_key}`)
    },
    init() {
      let that = this
      let userInfo = that.$store.state.userInfo
      // 默认demo教室
      var options = {
        prefixName: "e37361953",
        env: "production",
        // room_id: "20090381842899",
        room_id: "20092579671807",
        webrtc: 1
      };
      // 监课身份处理
      let _query = that.$route.query
      if(getQueryString('is_check')){
        _query.user_role = 0
        _query.user_status = 1
      }
      // 初始化配置信息
      options = Object.assign({}, options, {
        user_number: userInfo.id || 0,
        user_avatar: userInfo.avatar || '',
        user_name: userInfo.username || '',
        user_role: userInfo.is_assist,
      }, _query, BJY.query)
      !options.sign && (options.sign = that.makeSign(options, options.partner_key || ''))

      var classOption = {
        // 必须为字符串
        id: options.room_id,
        // 学生默认不限制发言
        speakState: 0
      };
      // BJY.config.SPEAK_STATE_LIMIT = 1
      if (Number(options.webrtc)) {
        classOption.webrtcType = Number(options.webrtc);
      }
      this.webrtc = classOption.webrtcType;
      let roomOptions = {
        env: options.env,
        privateDomainPrefix: options.prefixName,
        class: classOption,
        user: {
          number: options.user_number,
          avatar: decodeURIComponent(options.user_avatar),
          name: decodeURIComponent(options.user_name),
          type: Number(options.user_role),
          status: Number(options.user_status) || 0 // 是否隐身
        },
        teacher: {
          type: 1
        },
        sign: options.sign
      }
      // 补全老师信息
      if(userInfo.is_assist == 1){
        roomOptions.teacher.name = userInfo.username
        roomOptions.teacher.number = userInfo.id
        roomOptions.teacher.type = 1
        roomOptions.teacher.avatar = userInfo.avatar
      }
      BJY.init(roomOptions);
    },
    supportFlash() {
      var swf;
      var plugins = navigator.plugins;

      if (plugins && plugins.length > 0) {
        swf = plugins["Shockwave Flash"];
      } else if (document.all) {
        // eslint-disable-next-line no-undef
        swf = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
      }
      return !!swf;
    }
  }
};
</script>

<style lang="less">
@import "../../assets/iconfont/iconfont.css";
.action-list {
  height: 100%;
  width: 100%;
  overflow: hidden;
}
.room-main {
  height: 100vh;
}
#main {
  position: absolute;
  top: 0;
  width: 100%;
  height: 100%;
  opacity: 0;

  .class-panel {
    position: absolute;
    top: 0;
    left: 0;
    right: 290px;
    bottom: 40px;
    background-image: url("../../assets/img/class-panel-bg.jpg");
  }

  .media-panel {
    position: absolute;
    z-index: 1005;
    width: 290px;
    top: 0;
    right: 0;
    bottom: 40px;
    // padding: 8px 12px;
    box-sizing: border-box;
    background: #fff;
    box-shadow: -2px 0 6px rgba(0, 0, 0, 0.1);

    .live-teacher-player, .live-student-player {
      background: #000;
      height: 163px !important;
      width: 100%;
    }
    .screen {
      position: absolute;
      right: 30px;
      top: 30px;
      display: flex;
      justify-content: center;
      align-items: center;
      width: 180px;
      height: 60px;
      background: rgba(0,0,0,.5);
      border-radius: 10px;
      z-index: 9999;
      cursor: pointer;
      img {
        width: 20px;
        height: 20px;
      }
      span {
        font-size: 20px;
        font-family: Microsoft YaHei;
        font-weight: 400;
        line-height: 72px;
        color: #FFFFFF;
        margin-left: 12px;
      }
    }
  }

  .footer {
    position: absolute;
    z-index: 1002;
    left: 0;
    right: 0;
    bottom: 0;
    height: 40px;
    background-color: #424242;
    display: flex;
    justify-content: space-between;
    padding: 0 15px;
    align-items: center;
    font-size: 15px;
    color: #bdc6cf;
  }
}
</style>
